package com.geek.netty.demo;

import java.io.IOException;
import java.net.ServerSocket;
import java.net.Socket;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;

/**
 * @program netty-server
 * @description: nio ： 几百个连接还是可以的
 * @author: chanzhugang
 * @create: 2021/08/16 15:01
 */
public class DemoServer extends Thread {


    private ServerSocket serverSocket;

    @Override
    public void run() {
        try {
            // 启动 serverSocket
            serverSocket = new ServerSocket(8080);

            ExecutorService executorService = Executors.newFixedThreadPool(Runtime.getRuntime().availableProcessors());
            while (true) {
                // 阻塞等待客户端连接
                Socket socket = serverSocket.accept();
                RequestHandler handler = new RequestHandler(socket);

                // 开启线程处理，创建线程是大的开销
          //      handler.start();
                // 线程池处理
                executorService.execute(handler);
            }
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            if (serverSocket != null) {
                try {
                    serverSocket.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }
    }
}